package com.bit.bit_forum.service.impl;

import com.bit.bit_forum.common.AppResult;
import com.bit.bit_forum.common.ResultCode;
import com.bit.bit_forum.dao.ArticleMapper;
import com.bit.bit_forum.dao.UserMapper;
import com.bit.bit_forum.exception.ApplicationException;
import com.bit.bit_forum.model.Article;
import com.bit.bit_forum.model.Board;
import com.bit.bit_forum.model.User;
import com.bit.bit_forum.service.IArticleService;
import com.bit.bit_forum.service.IBoardService;
import com.bit.bit_forum.service.IUserService;
import com.bit.bit_forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContextException;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleServiceImpl implements IArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    private IBoardService boardService;
    @Autowired
    private UserMapper userMapper;

    @Override
    public void create(Article article) {
        //1.非空校验
        if(article==null || article.getBoardId()==null || article.getUserId()==null
                || StringUtil.isEmpty(article.getTitle())
                || StringUtil.isEmpty(article.getContent()) ){
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.设置默认值
        article.setVisitCount(0);
        article.setReplyCount(0);
        article.setLikeCount(0);
        article.setDeleteStat((byte)0);
        article.setState((byte)0);
//        这个获取到的时间比当前时间要晚8小时
//        Date date = new Date();
        // 直接在Instant上增加8小时，再转回Date
        Date date = Date.from(
                Instant.now().plus(8, ChronoUnit.HOURS)
        );
        article.setUpdateTime(date);
        article.setCreateTime(date);
        //写入数据库
        int n = articleMapper.insertSelective(article);
        if(n!=1){
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //更新用户的发帖数量
        //获取用户信息
        User user = userService.getById(article.getUserId());
        if(user==null){
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        userService.addOneArticleCountById(user.getId());

        //更新帖子板块
        Board board = boardService.getById(article.getBoardId());
        if(board==null){
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        boardService.addOneArticleCountById(board.getId());
    }

    @Override
    public List<Article> selectAll() {
        List<Article> articles = articleMapper.selectAll();
        return articles;
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        if(boardId==null || boardId<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Board board = boardService.getById(boardId);
        if(board==null){
//            板块不存在异常
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        //获取指定板块的帖子列表:
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);
        return articles;
    }

    @Override
    public Article selectDetailById(Long id) {
        //参数校验:
        if(id==null || id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectDetailById(id);
        if(article==null){
            //帖子不存在
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //更新帖子的访问数
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount()+1);
        //保存到数据库
        int n = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(n!=1){
            //服务器内部错误:
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //当前的article的访问量还未更新,更新后返回:
        article.setVisitCount(article.getVisitCount()+1);
        return article;
    }
//编辑帖子
    @Override
    public void modify(Long id, String title, String content) {
        //1.非空校验
        if(id==null || StringUtil.isEmpty(title) || StringUtil.isEmpty(content)){
            //参数非法：
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        //        这个获取到的时间比当前时间要晚8小时
//        Date date = new Date();
        // 直接在Instant上增加8小时，再转回Date
        Date date = Date.from(
                Instant.now().plus(8, ChronoUnit.HOURS)
        );
        updateArticle.setUpdateTime(date);//更新时间
        int n = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(n!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }
//    单独查询文章表中的帖子信息
    @Override
    public Article selectById(Long id) {
//        非空检验
        if(id==null || id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article==null){
//            打印 帖子不存在 日志：
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        return article;
    }

    @Override
    public void addLikeCountById(Long id) {
        //        非空检验
        if(id==null || id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article==null){
//            打印 帖子不存在 日志：
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setLikeCount(article.getLikeCount()+1);
        int n = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(n!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        log.info("点赞成功!");
    }

    @Override
    public void deleteById(Long id) {
        //参数校验：
        if(id==null || id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        //判断文章是否存在：
        if(article==null || article.getDeleteStat()==1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if(article.getState()==1){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setDeleteStat((byte)1);
        //        这个获取到的时间比当前时间要晚8小时
//        Date date = new Date();
        // 直接在Instant上增加8小时，再转回Date
        Date date = Date.from(
                Instant.now().plus(8, ChronoUnit.HOURS)
        );
        updateArticle.setUpdateTime(date);
        int n = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(n!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新板块中的帖子数量
        boardService.subOneArticleCountById(article.getBoardId());
        //更新用户表中的帖子数量：
        userService.subOneArticleCountById(article.getUserId());
    }
//       帖子回复数+1
    @Override
    public void addReplyCountById(Long id) {
        //参数校验：
        if(id==null || id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        //判断文章是否存在：
        if(article==null || article.getDeleteStat()==1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if(article.getState()==1){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setReplyCount(article.getReplyCount()+1);
        int n = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(n!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }
//  根据用户id查询用户的帖子列表
    @Override
    public List<Article> selectByUserId(Long userId) {
        //非空校验:
        if(userId==null || userId<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(userId);
        //对用户身份校验:
        if(user==null || user.getDeleteStat()==1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        List<Article> articles = articleMapper.selectByUserId(userId);
        return articles;
    }


}
